const http=require('http')
const fs=require('fs')
const url=require('url')
const mimes=require('./lib/mime')
const {join,extname}=require('path')

const rootpath=join(__dirname,'www')

http.createServer((req,res)=>{
    
    if(req.url!=='./favicon.ico'){
        let {pathname,query}=url.parse(req.url,true)
        pathname=pathname==='/'? './index.html' :pathname
        let filepath=join(rootpath,pathname)
        if(fs.existsSync(filepath)){
            const ext=extname(filepath).slice(1)
            const mime=mimes[ext]
            res.setHeader('content-type',mime)
            let html
          
            if('html'===ext){
                console.log(query)

                html=fs.readFileSync(filepath,'utf-8')
                html=html.replace(/\{\{\s*(\w+)\s*\}\}/g,function(preg,match){
                    return query[match]
                })
            }else{
                html=fs.readFileSync(filepath)
            }
            res.end(html) 
        }else{
            res.statusCode=404
            res.end(fs.readFileSync(errpath))
        }
    }
}).listen(3000,'0.0.0.0')